<template>
  <block v-if="initData">
    <FirmwareUpdateView :ha-id="haId" :ota-helper="otaHelper" />
  </block>
</template>

<script setup lang="ts">
import { onLoad, onUnload } from '@dcloudio/uni-app'
import FirmwareUpdateView from './firmwareUpdateView.vue'
import type { OTAHelper } from './helpers/types'
import { createOtaHelper } from './helpers/index'
import { useApplianceStore } from '@/store/appliance'
import type { ApplianceData } from '@/types/appliance'
import { showLoading } from '@/utils/mpHelper'
import { getApplianceDetail } from '@/api/appliance'

const applianceStore = useApplianceStore()
const haId = ref('')
const initData = ref(false)

let otaHelper: OTAHelper | null = null

onLoad(async (query: any) => {
  // 获取当前家电信息
  let appliance: ApplianceData | null = null
  const queryHaid = query.haid || query.haId
  if (queryHaid) {
    try {
      const detailRes = await showLoading(() => getApplianceDetail(queryHaid))
      appliance = detailRes.data
    } catch (e) {
      console.error(e)
    }
  } else {
    appliance = applianceStore.current
  }

  // 创建固件升级方法
  otaHelper = createOtaHelper({
    brand: appliance?.brand || '',
    type: appliance?.type || '',
    vib: appliance?.vib || '',
    haId: appliance?.haId || '',
    scene: 'firmware',
  })

  haId.value = appliance?.haId || ''

  nextTick(() => {
    initData.value = true
  })
})
onUnload(() => {
  otaHelper?.destroy()
})
</script>
